<template>
  <div class="callback-container">
    <div class="callback-box">
      <el-icon class="loading-icon" :size="60">
        <Loading />
      </el-icon>
      <h2>正在处理钉钉登录...</h2>
      <p>请稍候</p>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

onMounted(async () => {
  // 从 URL 获取授权码
  const code = route.query.code

  if (!code) {
    ElMessage.error('未获取到授权码，请重新登录')
    router.push('/login')
    return
  }

  try {
    // 直接调用后端回调接口
    const response = await fetch(
      `http://127.0.0.1:8000/users/dingtalkcallback?code=${code}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '钉钉登录失败')
    }

    const data = await response.json()

    // 保存 token 和用户信息
    userStore.setToken(data.token, data.refresh_token)
    userStore.setUserInfo(data.user)
    localStorage.setItem('userInfo', JSON.stringify(data.user))

    ElMessage.success('钉钉登录成功！')

    // 跳转到首页
    setTimeout(() => {
      router.push('/')
    }, 500)
  } catch (error) {
    console.error('钉钉登录失败:', error)
    ElMessage.error(error.message || '钉钉登录失败，请重试')
    
    setTimeout(() => {
      router.push('/login')
    }, 2000)
  }
})
</script>

<style scoped>
.callback-container {
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  padding: 20px;
}

.callback-box {
  text-align: center;
  background: white;
  border-radius: 12px;
  padding: 40px 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 320px;
}

.loading-icon {
  color: #409eff;
  animation: rotate 1.5s linear infinite;
  margin-bottom: 20px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.callback-box h2 {
  font-size: 22px;
  color: #303133;
  margin: 20px 0 10px 0;
  font-weight: 500;
}

.callback-box p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}
</style>

